'use strict';

module.exports = app => {
  const DataTypes = app.Sequelize;

  const Model = app.model.define('t_admin_users', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
    },
    user_no: {
      type: DataTypes.STRING(15),
      allowNull: false,
      primaryKey: true,
    },
    phone: {
      type: DataTypes.STRING(11),
      allowNull: false,
    },
    avatar: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    username: {
      type: DataTypes.STRING(15),
      allowNull: true,
    },
    password: {
      type: DataTypes.STRING(255),
      allowNull: false,
    },
    email: {
      type: DataTypes.STRING(20),
      allowNull: true,
    },
    gender: {
      type: DataTypes.INTEGER(2),
      allowNull: true,
      defaultValue: '3',
    },
    type: {
      type: DataTypes.INTEGER(2),
      allowNull: true,
    },
    state: {
      type: DataTypes.INTEGER(1),
      allowNull: false,
    },
    remark: {
      type: DataTypes.STRING(255),
      allowNull: true,
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    deleted_at: {
      type: DataTypes.DATE,
      allowNull: true,
    },
  },
  {
    paranoid: true, // 如果我们开启了paranoid（偏执）模式，destroy的时候不会执行DELETE语句，而是执行一个UPDATE语句将deleted_at字段设置为当前时间
    defaultScope: {
      attributes: { exclude: [ 'password' ] },
    },
    scopes: {
      withPassword: {
        attributes: {},
      },
    },
  });

  Model.associate = function() {
    // 与roles存在多对多关系，使用belongsToMany()
    app.model.TAdminUsers.belongsToMany(app.model.TRoles, {
      through: app.model.TRolesUsers,
      foreignKey: 'user_id',
      otherKey: 'role_id',
    });
  };

  return Model;
};
